﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MyVoteMVC.Data.Repositories;
using MyVoteMVC.Domain;
using System.Reflection;
using MyVoteMVC.Common;

namespace MyVoteMVC
{
    public static class VoteFactory
    {
        static VoteFactory() {
            //RegisterTypeMapping<IUnitOfWork, VoteDBUnitOfWork>();
            //RegisterTypeMapping<IRepository<VT_Activities>, ActivityRepository>();
            //RegisterTypeMapping<IRepository<VT_Items>, ItemRepository>();
            //RegisterTypeMapping<IRepository<VT_Messages>, MessageRepository>();
            //RegisterTypeMapping<IRepository<VT_Questions>, QuestionRepository>();
            //RegisterTypeMapping<IRepository<VT_Tickets>, TicketRepository>();
            //RegisterTypeMapping<IRepository<VT_Users>, UserRepository>();
        }
        private static Dictionary<Type, Type> classTypes = new Dictionary<Type, Type>();

        public static TEntity GetInstance<TEntity>(params object[] args) where TEntity : class
        {
            if (classTypes.ContainsKey(typeof(TEntity)))
            {
                Type internalFactory = typeof(InternalFactory<,>);

                internalFactory = internalFactory.MakeGenericType(typeof(TEntity), classTypes[typeof(TEntity)]);

                MethodInfo method = internalFactory.GetMethod("Create", BindingFlags.Static | BindingFlags.NonPublic);

                return (TEntity)method.Invoke(

                    internalFactory, new object[] { args });
            }
            else
            {
                throw new Exception("类型: " + typeof(TEntity)
                    + " 未注册");
            }
        }

        public static void RegisterTypeMapping<I, C>()
        {
            if (!classTypes.ContainsKey(typeof(I)))
            {
                classTypes.Add(typeof(I), typeof(C));
            }
        }
    }
}
